<template>
    <!-- <div> -->
    <el-card style="height: 80px;">
        <el-form :inline="true" class="form">
            <el-form-item label="昵称:">
                <el-input placeholder="请你输入搜索关键字" v-model="keyword"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="default" :disabled="keyword ? false : true" @click="search">搜索</el-button>
                <!-- <el-button type="primary" size="default" @click="reset">重置</el-button> -->
            </el-form-item>
        </el-form>
    </el-card>
    <el-card class="box-card" style="margin: 10px 0px;">
        <!-- 卡片顶部添加品牌按钮 -->
        <el-button type="primary" size="default" icon="Plus" @click="showAddDialog"
            v-has="`btn.Trademark.add`">添加</el-button>
        <!-- 表格组件：用于展示已有得平台数据 -->
        <!-- table:---border:可以设置表格纵向是否有边框
                table-column:---label:某一个列表 ---width:设置这列宽度 ---align:设置这一列对齐方式    
            -->
        <el-table style="margin:10px 0px" border :data="tableValuekArr">
            <el-table-column label="姓名" prop="name" width="90px"></el-table-column>
            <el-table-column label="昵称" prop="nickName" width="100px"></el-table-column>
            <el-table-column label="电话" prop="mobile" width="130px"></el-table-column>
            <el-table-column label="邮箱" prop="email" width="200px"></el-table-column>
            <el-table-column label="锁定" width="80px">
                <template #="{ row, $index }">
                    <el-icon :color="iconColor(row.locked)" :title="iconTitle(row.locked)">
                        <component :is="row.locked === 1 ? 'Close' : 'Select'"></component>
                    </el-icon>
                </template>
            </el-table-column>
            <el-table-column label="简介" prop="profile"></el-table-column>
            <el-table-column label="更新时间" prop="ctime"  width="170px"></el-table-column>

            <el-table-column label="操作" width="120px">
                <template #="{ row, $index }">
                    <el-button type="primary" size="small" icon="Edit" @click="update(row)"></el-button>
                    <el-popconfirm :title="`您确定要删除【${row.typeName}?】`" width="250px" icon="Delete"
                        @confirm='remove(row.typeId)'>
                        <template #reference>
                            <el-button type="warning" size="small" icon="Delete"></el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[5, 7, 9, 11]"
            :background="true" layout="prev, pager, next, jumper,->,sizes,total" :total="total"
            @current-change="getWriterList" @size-change="handler" />
    </el-card>

    <el-dialog v-model="dialogFormVisible" :title="formParams.authorId ? '修改' : '添加'">
        <el-form style="width: 80%;" :model="formParams" :rules="rules" ref="formRef" label-width="100px">
            <el-form-item label="姓名" prop="name">
                <el-input placeholder="请输入姓名" v-model="formParams.name"></el-input>
            </el-form-item>
            <el-form-item label="昵称" prop="nickName">
                <el-input placeholder="请输入昵称" v-model="formParams.nickName"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
                <el-input placeholder="电话" v-model="formParams.mobile"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input placeholder="邮箱" v-model="formParams.email"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input placeholder="密码" v-model="formParams.password"></el-input>
            </el-form-item>
            <el-form-item label="简介" prop="profile">
                <el-input placeholder="简介" v-model="formParams.profile"></el-input>
            </el-form-item>
            <el-form-item label="状态" prop="locked">
                <el-radio-group v-model="formParams.locked" class="ml-4">
                    <el-radio :label='1' size="large">锁定</el-radio>
                    <el-radio :label='0' size="large">正常</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="图片" prop="headImg">
                <!-- upload组件属性:action图片上传路径书写/api,代理服务器不发送这次post请求  -->
                <el-upload class="avatar-uploader" action="/api/v1/m/upload" :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload" :on-preview="handlePictureCardPreview" :show-file-list="false">
                    <img v-if="formParams.headImg" :src="formParams.headImg" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <!-- 具名插槽:footer -->
        <template #footer>
            <el-button type="primary" size="default" @click="cancel">取消</el-button>
            <el-button type="primary" size="default" @click="confirm">确定</el-button>
        </template>
    </el-dialog>

    <el-dialog v-model="img_dialogVisible">
        <img :style="{ width: '100%' }" :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
    <!-- </div> -->
</template>

<script setup lang="ts">
import { ElMessage, UploadProps } from 'element-plus'
//引入组合式API函数ref
import { ref, onMounted, reactive, nextTick } from 'vue';
import { reqWriterList, reqAddOrUpdateWriter, reqDeleteWriter } from '@/api/acl/writer';
import type { TWriterListResponseData, TWriter, Records } from '@/api/acl/writer/type'

//默认页码
let pageNo = ref<number>(1);
//一页展示几条数据
let pageSize = ref<number>(5);
//用户总个数
let total = ref<number>(0);
let keyword = ref<string>('');

let img_dialogVisible = ref<boolean>(false)
let dialogImageUrl = ref('')

//存储已有品牌的数据
let tableValuekArr = ref<Records>([]);
//控制对话框显示与隐藏
let dialogFormVisible = ref<boolean>(false)

const iconColor = (locked:number) => locked === 1 ? 'red' : 'green';
const iconTitle = (locked:number) => locked === 1 ? '锁定' : '正常';

//定义收集表单数据
let formParams = reactive<TWriter>({
    nickName: '',
    headImg: '',
    /**
     * 0未锁定，1锁定
     */
    locked: 0,
})
//获取el-form组件实例
let formRef = ref();

const search = () => {
    //根据关键字获取相应的用户数据
    getWriterList();
    //清空关键字
    keyword.value = '';
}

//按昵称搜索
const getWriterList = async (pager = 1) => {
    //当前页码
    pageNo.value = pager;
    let result: TWriterListResponseData = await reqWriterList(pageNo.value, pageSize.value, keyword.value);
    if (result.code == 0) {
        total.value = result.data.total
        tableValuekArr.value = result.data.list;
    }
}

//分页器下拉菜单的自定义事件的回调
const handler = () => {
    getWriterList();
}

//组件挂载完毕钩子---发一次请求,获取第一页、一页三个已有品牌数据
onMounted(() => {
    getWriterList();
});

const resetForms = () => {
    formParams.authorId = ''
    formParams.name = ''
    formParams.nickName = ''
    formParams.mobile = ''
    formParams.email = ''
    formParams.headImg = ''
    formParams.password = ''
    /**
     * 0未锁定，1锁定
     */
    formParams.locked = 0
    formParams.profile = ''
}

const clearValidate = () => {
    //第一种写法:ts的问号语法
    // formRef.value?.clearValidate('tmName');
    // formRef.value?.clearValidate('logoUrl');
    if (formRef.value) {
        formRef.value.clearValidate('typeName');
        formRef.value.clearValidate('logo');
    }
}
//添加品牌按钮的回调
const showAddDialog = () => {
    //对话框显示
    dialogFormVisible.value = true;
    //清空收集数据
    resetForms()

    nextTick(() => {
        clearValidate()
    })
}

//修改已有品牌的按钮的回调
//row:row即为当前已有的品牌
const update = (row: TWriter) => {
    //清空校验规则错误提示信息
    nextTick(() => {
        clearValidate()
    })
    //对话框显示
    dialogFormVisible.value = true;
    //ES6语法合并对象
    Object.assign(formParams, row);
}
//对话框底部取消按钮
const cancel = () => {
    //对话框隐藏
    dialogFormVisible.value = false;
}
const confirm = async () => {
    //在你发请求之前,要对于整个表单进行校验
    //调用这个方法进行全部表单相校验,如果校验全部通过，在执行后面的语法
    await formRef.value.validate();
    let result: any = await reqAddOrUpdateWriter(formParams);
    //添加|修改已有品牌
    if (result.code == 0) {
        //关闭对话框
        dialogFormVisible.value = false;
        //弹出提示信息
        ElMessage({
            type: 'success',
            message: formParams.authorId ? '修改成功' : '添加成功'
        });
        //再次发请求获取已有全部的品牌数据
        getWriterList(pageNo.value);
    } else {
        //添加品牌失败
        ElMessage({
            type: 'error',
            message: formParams.authorId ? '修改失败' : '添加失败'
        });
        //关闭对话框
        dialogFormVisible.value = false;
    }
}
//上传图片组件->上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    //钩子是在图片上传成功之前触发,上传文件之前可以约束文件类型与大小
    //要求:上传文件格式png|jpg|gif 4M
    if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif') {
        if (rawFile.size / 1024 / 1024 < 4) {
            return true;
        } else {
            ElMessage({
                type: 'error',
                message: '上传文件大小小于4M'
            })
            return false;
        }
    } else {
        ElMessage({
            type: 'error',
            message: "上传文件格式务必PNG|JPG|GIF"
        })
        return false;
    }
}
//图片上传成功钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    //response:即为当前这次上传图片post请求服务器返回的数据
    //收集上传图片的地址,添加一个新的品牌的时候带给服务器
    formParams.headImg = response.data.url;
    //图片上传成功,清除掉对应图片校验结果
    formRef.value.clearValidate('logo');

}

//品牌自定义校验规则方法
const validatorTmName = (rule: any, value: any, callBack: any) => {
    //是当表单元素触发blur时候,会触发此方法
    //自定义校验规则
    if (value.trim().length >= 2) {
        callBack();
    } else {
        //校验未通过返回的错误的提示信息
        callBack(new Error('名称位数大于等于两位'))
    }
}
//品牌LOGO图片的自定义校验规则方法
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
    //如果图片上传
    if (value) {
        callBack();
    } else {
        callBack(new Error('LOGO图片务必上传'))
    }
}

//表单校验规则对象
const rules = {
    typeName: [
        //required:这个字段务必校验,表单项前面出来五角星
        //trigger:代表触发校验规则时机[blur、change]
        { required: true, trigger: 'blur', validator: validatorTmName }
    ],
    logo: [
        { required: true, validator: validatorLogoUrl }
    ]
}
//气泡确认框确定按钮的回调
const remove = async (id: string) => {
    //点击确定按钮删除已有品牌请求
    let result = await reqDeleteWriter(id);
    if (result.code == 0) {
        //删除成功提示信息
        ElMessage({
            type: 'success',
            message: '删除成功'
        });
        //再次获取已有的品牌数据
        getWriterList(tableValuekArr.value.length > 1 ? pageNo.value : pageNo.value - 1);
    } else {
        ElMessage({
            type: 'error',
            message: '删除失败'
        })
    }
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    console.log(uploadFile)
    //   dialogImageUrl.value = uploadFile.url!
    //   dialogVisible.value = true
}

const previewImage = (row: TWriter) => {
    img_dialogVisible.value = true
    if (row.headImg !== undefined) {
        dialogImageUrl.value = row.headImg;
    }
}


</script>
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>